<?php

namespace app\stores\controller\product;

use think\Controller;

class Product extends Controller{
    public function __construct()
    {
        parent::__construct();

        $this->TypeModel=model('Product.Type');
        $this->ProductModel=model('Product.Product');
        $this->UserModel=model('User.User');
        $this->VipModel=model('Product.Vip');
    }

    public function index(){
        $Type=$this->TypeModel->limit(6)->select();
        $Recommend=$this->ProductModel->with(['type'])->where(['flag'=>3])->order('id','desc')->limit(4)->select();
        $News=$this->ProductModel->with(['type'])->where(['flag'=>2])->order('id','desc')->limit(4)->select();
        $Hot=$this->ProductModel->with(['type'])->where(['flag'=>1])->order('id','desc')->limit(4)->select();


        $data=[
            'Type'=>$Type,
            'Recommend'=>$Recommend,
            'News'=>$News,
            'Hot'=>$Hot,
        ];

        $this->success('返回首页数据',null,$data);
        exit;
    }

    public function type()
    {
        if($this->request->isPost())
        {
            $typeid = $this->request->param('typeid', 0);
            $flag = $this->request->param('flag', 0);
            $orderby = $this->request->param('orderby', 'id');
            $keywords = $this->request->param('keywords', '');
            $where = [];

            $type = $this->TypeModel->find($typeid);

            //有分类查询分类的产品，没有分类查询全部
            if($type)
            {
                $where['typeid'] = $typeid;
            }

            //判断是否有选择属性
            if($flag)
            {
                $where['flag'] = $flag;
            }

            if(!empty($keywords))
            {
                $where['name'] = ['like',"%$keywords%"];
            }

            //获取商品列表
            $prolist = $this->ProductModel->where($where)->order($orderby, 'desc')->select();

            $this->success('查询商品数据成功', null, $prolist);
            exit;
        }
    }

    public function info()
    {
        if($this->request->isPost())
        {
            //获取商品的id
            $proid = $this->request->param('proid', 0);
            $userid = $this->request->param('userid', 0);

            //查询商品的详细
            $product = $this->ProductModel->with(['type'])->find($proid);

            if(!$product)
            {
                $this->error('商品不存在');
                exit;
            }

            $user = $this->UserModel->find($userid);
            $vip = isset($user) ? $user['vip'] : 0;

            if($vip > 0)
            {
                $level = $this->VipModel->where(['proid' => $proid, 'level' => $vip])->value('price');
                $product['level'] = $level;
            }

            $this->success('返回商品详情', null, $product);
            exit;
        }

    }
}